#!/bin/bash

# product
# version
# release
# repo_url
# packages
# upload_image_dir

. ${LKP_SRC}/lib/upload.sh
. ${LKP_SRC}/lib/debug.sh
. ${LKP_SRC}/lib/create_compile_env.sh

init_image_tailor()
{
	if rpm -q imageTailor &> /dev/null; then
		yum remove -y imageTailor
	fi
	yum install -y imageTailor sudo -c ${yum_conf} || die "install imageTailor error."
	sed -i 's#IMG_SIZE=3#IMG_SIZE=40#g' /opt/imageTailor/custom/cfg_qcow2/bin/create-image
	sed -i '/#disbale other repos/i \cp /etc/resolv.conf ${TARGET_ROOT}/etc/' /opt/imageTailor/custom/cfg_qcow2/hooks/root.d/01-create-root
	sed -i '/most reliable/i \rm -f ${TARGET_ROOT}/etc/resolv.conf' /opt/imageTailor/custom/cfg_qcow2/hooks/root.d/01-create-root
}

modify_config_file()
{
	config_path="/opt/imageTailor/custom/cfg_qcow2/config"
	repo_file="${config_path}/repo"
	rpmlist_file="${config_path}/rpmlist"
	
	rm -f ${repo_file} && touch ${repo_file}
	for repo in ${repo_url[@]}
	do
		echo "${repo}" >> ${repo_file}
	done

	for pkg in ${packages[@]}
	do
		echo "${pkg}" >> ${rpmlist_file}
	done
}

build_image()
{
	cd /opt/imageTailor/
	./mkdliso -p qcow2 -c custom/cfg_qcow2
}


upload_image()
{
	ARCH="$(uname -i)"
	if [ -n "${release}" ];then
		qcow2_name="${product}-${version}-${release}-${ARCH}.qcow2"
	else
		qcow2_name="${product}-${version}-${ARCH}.qcow2"
	fi

	cd "/opt/imageTailor/result/$(date +%Y)"*
	if [ ! -s "openEuler_${ARCH}.qcow2" ];then
		die "make qcow2 failed."
	else
		mv openEuler_${ARCH}.qcow2 ${qcow2_name}
		xz -T 0 -9 --lzma2=dict=8MiB "${qcow2_name}"
		hmi_qcow2=$(ls *.qcow2.xz)
		sha256sum ${hmi_qcow2} > "${hmi_qcow2}.sha256sum"
		upload_one_curl "${hmi_qcow2}" ${upload_image_dir}
		if [ $? -ne 0 ];then
			die "upload image failed."
		fi
		upload_one_curl "${hmi_qcow2}.sha256sum" ${upload_image_dir}
		if [ $? -ne 0 ];then
			die "upload sha256sum failed."
		fi
	fi
}

build_qcow2_image()
{
	config_env_repo
	init_image_tailor
	modify_config_file
	build_image
	upload_image
}

trap abnormal_exit EXIT

build_qcow2_image
if [ $? -eq 0 ];then
	status="success"
fi
